<template>
    <view class="work" id="equipmeny-work" v-if="indicatorslength > 0">
        <view class="card work-info">
            <template >
                <view class="head">
                    <view class="bd">更新时间： {{ updateTime }}</view>
                </view>
            </template>
            <view class="body">
                <view class="status">
                    <view class="item" v-for="item in indicators" :key="item.value">
						<template>
							<view class="num" :style="{color: (item.status == 1? 'red' :'#fff')}">
								{{ item.value }}
								<UniIcon class="upicon" v-if="[3,5].indexOf(item.operator) == 0 && item.index > 0" :size="20" :type="'pulldown'" :color="item.error_color" />
								<UniIcon v-if="[4,6].indexOf(item.operator) == 0 && item.index > 0 " :size="20" :type="'pulldown'" :color="item.error_color" />
							</view>
						</template>
                        <view class="name" :style="{color: (item.status == 1? 'red' :'#fff')}">
							{{item.name}}
                            
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <view class="card indicator">
            <view class="head">
                <view class="title">磨粒趋势</view>
                <scroll-view class="tags" :scroll-x="true" :scrollX="true">
                    <view
                        class="tag"
                        :class="{ active: tagdata.name === form.target }"
                        v-for="(tagdata, tIndex) in indicators"
                        :key="tIndex"
                        @click="onClickTarget(tagdata, tIndex)"
						>
                        {{ tagdata.name }}
                    </view>
                </scroll-view>
            </view>
            <view class="body">
                <view class="chart-tip">
                    <view class="bd">
                        <template v-if="currentTag">
                          安全阈值：{{safetyThreshold}}
                        </template>
                    </view>
                </view>
                <view class="w-chart">
                    <l-echart  id="oil-chart"  ref="chart" v-show="showOil && showEchart"></l-echart>
                    <view class="no" v-if="!showEchart">
                        <image :src="imgBaseUrlV2 + 'yujing_info.png'"  mode=""  class="no-icon"/>
                        未安装{{ displayName }}传感器
                    </view>
                </view>
            </view>
            <view class="ft">
                <view class="modes">
                    <view
                        class="mode"
                        :class="{ active: mode.id === form.mode }"
                        v-for="(mode, mIndex) in modes"
                        :key="mIndex"
                        @click="onClickMode(mode, mIndex)"
                      >
                        {{ mode.name }}
                    </view>
                </view>
            </view>
        </view>
        <Message ref="message"></Message>
    </view>
        <view style="color: #fff;text-align: center;" v-else>暂无数据</view>
</template>

<script>
import { imgBaseUrlV2 } from "@/common/config";
import * as echarts from "@/pageA/lime-echart/echarts";
import lEchart from "@/pageA/lime-echart/index";
import UniIcon from "@/components/uni-icons/uni-icons.vue"
import detailModule from "@/common/mixins/detail-module";
import {
    getDeviceRadarData,
    getDeviceBrokenLineData,
	getDeviceSyntheticData
} from "@/common/api/equipment";
const colors = [
    "#F19149",
    "#6CE0EF",
    "#F7BC3B",
    "#3F7DFF",
    "#5470c6",
    "#91cc75",
    "#fac858",
    "#ee6666",
    "#73c0de",
];
const areaStyle = {
  //区域填充样式
    normal: {
        //线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
        color: new echarts.graphic.LinearGradient(0,0,0,1,[
                {
                  offset: 0,
                  color: "rgba(115, 180, 255, 0.7)",
                },
                {
                  offset: 1,
                  color: "rgba(63, 125, 255, 0)",
                },
            ],
            false
        ),
        shadowColor: "rgba(53,142,215, 0.3)", //阴影颜色
        shadowBlur: 20, //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
    },
};
export default {
    mixins: [detailModule],
    components: {
        lEchart,
        UniIcon
    },
    props: {
        device_id: {
          type: [String, Number],
          default: "",
        },
        typeinfo:{
            type:[String,Number],
            default:2,
        },
        type_id:{
            type: [String,Number],
            default: null,
        },
        info: {
            type: Object,
            default() {
                return {
                    updateDate: "2021-05-10 18:23:55",
                    vpt: 112,
                };
            },
        },
    },
    data() {
        return {
			safetyThreshold:"",//安全阈值
			vibration:[],
			indicatorslength:0,
            showOil: true,
            showEchart: true,
            showFilter: false,
            imgBaseUrlV2,
            currentTag: null,
            colors,
            updateTime: "",
            displayName: "磨粒",
            dataForm: {},
            modes: [
                {
                  id: "1",
                  name: "1H",
                },
                {
                  id: "2",
                  name: "12H",
                },
                {
                  id: "3",
                  name: "24H",
                },
                {
                  id: "4",
                  name: "周",
                },
                {
                  id: "5",
                  name: "月",
                },
            ],
            form: {
                mode: "1",
                target: "",
            },
            tags: [],
            indicators: [],
            option: {
                tooltip: {
                    trigger: "axis",
                    position: [10, 10],
                    formatter(data) {
                        let arr = data.map((i, index) => {
                            return `时间:${i.axisValue}\n${i.seriesName}: ${
                                i.data !== null ? i.data : "-"
                            }`;
                        });
                        return arr.join("\n");
                    },
                    backgroundColor: "rgba(0,0,0,0.7)",
                    borderColor: "none",
                    textStyle: {
                        color: "#fff",
                    },
                },
                grid: {
                    top: 15,
                    left: 30,
                    right: 5,
                    bottom: 30,
                },
                xAxis: [{
                    type: "category",
                    boundaryGap: true,
                    axisLine: {
                        //坐标轴轴线相关设置。数学上的x轴
                        show: false,
                        lineStyle: {
                            color: "#f9f9f9",
                        },
                    },
                    axisLabel: {
                      //坐标轴刻度标签的相关设置
                        textStyle: {
                            color: "#D8D8D8",
                        },
                        rotate: 45,
                    },
                    axisTick: {
                        show: false,
                    },
                    boundaryGap: false,
                    splitLine: { show: false },
                    minorSplitLine: {
                        show: false,
                    },
                    data: [],
                  },
                ],
                yAxis: [{
                    type: "value",
                    min: 0,
                    splitNumber: 7,
                    splitLine: { show: false },
                    minorSplitLine: {
                        show: false,
                    },
                    min: function (value) {
                        return parseInt(value.min || 1) - 20;
                    },
                    max: function (value) {
                        return parseInt(value.max || 1) + 20;
                    },
                    axisLine: {
                        show: false,
                    },
                    axisLabel: {
                        textStyle: {
                            color: "#D8D8D8",
                        },
                    },
                    axisTick: {
                        show: false,
                    },
                  },
                ],
                series: [],
            },
        };
    },
    methods: {
		getDeviceSyntheticsData(){
			if (!this.device_id) return;
            uni.showLoading({
                title: "加载中",
            });
			return getDeviceSyntheticData({
				device_id: this.device_id,
				type_id: this.type_id
			}).then((res) => {
				if (res.code !== this.$ERR_OK) {
					return this.message.error(res.message || "获取综合概况数据失败");
				}
				let data = res.data[0] || [];
				this.updateTime = data.updateTime;
				this.indicatorslength = data.list.length;
				this.indicators = data.list
				this.currentTag = this.indicators[0]["name"];
				this.form.target = this.currentTag
                this.getChartData();
				this.safetyThresholdList(data.list[0]);
				uni.hideLoading(); // 异常时也需关闭
			}).catch((err) => {
                uni.hideLoading(); // 异常时也需关闭
            });
		},
       
        transValue(v) {
            let tv = v + "";
            if (tv.indexOf(".") === -1) return v;
            let n = Number(v) || 0;
            return Number(n.toFixed(3));
        },
        getChartData() {
            this.$refs.chart?.clear();
            let { currentTag } = this;
			
            if (!currentTag) return;
            let key = this.form.target;
            let form = {
                device_id: this.device_id,
                rules: key,
                record_count: 40,
                time_type: this.form.mode,
            };
			
            return getDeviceBrokenLineData(form).then((res) => {
                if (res.code !== this.$ERR_OK) {
                    this._initChart = false;
                    return (this.showEchart = false);
                }
                this.showEchart = true;
                let data = res.data;
                let option = this.option;
			
                let format = form.time_type == "4" || form.time_type == "5" ? "MM-DD" : "HH:mm";
                option.xAxis[0].data = data.map((i) => {
					
                    return this.$moment(i.time).format(format);
                });
				
                let tmp = {};
                let maxlength = 2;
                data.map((i) => {
                    let list = i.list || [];
					if (!tmp[list.name]) {
					  tmp[list.name] = [];
					}
					let v = Number(list.value || "0") + "";
					let intV = parseInt(v) + "";
					if (intV.length > maxlength) {
					    maxlength = intV.length;
					}

					tmp[list.name].push(list.value !== undefined && list.value !== null ? v : null)
                });
                option.grid.left = maxlength * 11;
                let data2 = Array.isArray(tmp[key])? tmp[key].filter((i) => i).length? tmp[key] || []: []: [];
                option.series = [{
                    name: this.form.target,
                    type: "line",
                    showSymbol: false,
                    areaStyle,
                    markPoint: {},
                    data: data2,
                }];
                this.option = option;
                console.log(tmp, "???tmp", option);
                this.initChart();
            }).catch((err) => {});
        },
        initChart() {
            if (this._initChart) {
                if (!this.option.series[0].data || !this.option.series[0].data.length) {
                    this.$refs.chart.clear();
                }
                return this.$refs.chart.setOption(this.option);
            }
        this.$nextTick(() => {
            this.$refs.chart &&
                this.$refs.chart.init((config) => {
                    console.log("clear");
                    const { canvas } = config;
                    const chart = echarts.init(canvas, null, config);
                    canvas.setChart(chart);
                    chart.setOption(this.option);

                    this._initChart = true;
                    // 需要把 chart 返回
                    return chart;
                });
            });
        },
		
		safetyThresholdList(tag){
			this.safetyThreshold = "";
			const currentTag = this.form.target;
			if (tag.safetyThreshold.length) {
				const operatorMap = {
					1: '=',
					2: '!=',
					3: '>',
					4: '<',
					5: '>=',
					6: '<='
				}
				const conditions = tag.safetyThreshold.map((safety, index) => {
					const operator = operatorMap[safety.operator];
					if (!operator) {
					  console.warn(`Invalid operator: ${safety.operator}`);
					  return '';
					}
					return `${currentTag}${operator}${safety.value}`;
				}).filter(Boolean);
				this.safetyThreshold = conditions.join('，');
			}
		},
		
        onClickTarget(tag, index) {
            this.form.target = tag.name;
            this.currentTag = tag;
            this.getChartData();
            this.safetyThresholdList(tag)
        },
        onClickMode(mode) {
            this.form.mode = mode.id;
            this.getChartData();
        },
        onShowFilter() {
            this.showFilter = !this.showFilter;
        },
        onConfirmFilter(i, index) {
            this.showFilter = false;
            let tagIndex = this.currentTag? this.tags.findIndex((i) => i.field_key === this.currentTag.field_key): -1;
            if (tagIndex > -1) {
                console.log(this.tags.slice(0), this.currentTag);
                this.currentTag.filter = index;
                this.tags.splice(tagIndex, 1, this.currentTag);
            }
            this.getChartData();
        },
    },
    mounted() {
        this.$nextTick(() => {
            this.getDeviceSyntheticsData();
        });
    },
    watch: {

    },
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/variable';

.no {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: 400;
  font-family: PingFangSC-Regular, PingFang SC;
  color: color-desc;

  &-icon {
    display: flex;
    width: 36rpx;
    height: 36rpx;
    margin-right: 12rpx;
  }
}

.work-info {
  padding: 30rpx 24rpx 40rpx;

  >.head {
    display: flex;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: color-white;
    line-height: 1;
    margin-bottom: 24rpx;

    >.bd {
      flex: 1;
    }

    >.ft {
      display: flex;
      flex: 0 0 auto;
      align-items: center;

      >.icon {
        display: block;
        width: 30rpx;
        height: 30rpx;
        margin-left: 8rpx;
      }
    }
  }
}

.card {
  margin: 0 24rpx;
  background: #1A3156;
  border-radius : 10rpx;
}

.status {
  display: flex;
  flex-wrap: wrap;

  >.item {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-width: 33.33%;
    max-width: 33.34%;
    align-items: center;
    justify-content: center;
    margin-top: 20rpx;

    &:nth-child(-n+3) {
      margin-top: 0;
    }

    >.no-status {
      width: 72rpx;
      height: 20rpx;
      background: #EEEEEE;
      margin-bottom: 19rpx;
      margin-top: 20rpx;
    }

    >.num {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 36rpx;
      line-height: 52rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 600;
      color: color-white;
      margin-bottom: 6rpx;

      &.danger {
        color: color-danger;
      }

      &.success {
        color: color-success;
      }
	  .upicon {
		display: inline-block;
		transform: scaleY(-1);  
	  }

      >.icon {
        width: 32rpx;
        height: 32rpx;
        margin-left: 12rpx;
        margin-top: 2rpx;
      }
    }

    >.name {
      font-size: 24rpx;
      line-height: 1;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: color-desc;
    }
  }
}

.indicator {
  margin-top: 30rpx;
  padding: 24rpx 0;

  >.head {
    padding: 0 24rpx;

    >.title {
      font-size: 32rpx;
      line-height: 1;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 600;
      color: color-white;
      padding: 6rpx 0;
    }

    >.tags {
      display: flex;
      padding: 14rpx 0;
      border-bottom: 1rpx solid #eee;
      height: 78rpx;
      box-sizing: border-box;
      white-space: nowrap;

      .tag {
        display: inline-block;
        flex: 0 0 auto;
        min-width: 70rpx;
        padding: 0 14rpx;
        height: 48rpx;
        line-height: 48rpx;
        text-align: center;
        color: color-describe;
        font-size: 24rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        border-radius: 4rpx;
        margin-right: 10rpx;
        background: #d8d8d8;

        &.active {
          background: #6B7495;
          color: #fff;
        }
      }
    }
  }

  >.body {
    padding: 0 18rpx;

    >.w-chart {
      position: relative;
      height: 440rpx;

      >.no {
        position: relative;
        display: flex;
        width: 100%;
        height: 100%;
        align-items: center;
        justify-content: center;
      }
    }
  }

  >.ft {
    padding: 0 24rpx;

    .modes {
      display: flex;
      margin-top: 20rpx;

      >.mode {
        flex: 0 0 auto;
        width: 100rpx;
        height: 48rpx;
        line-height: 44rpx;
        border-radius: 4rpx;
        border: 2rpx solid #C9CACA;
        text-align: center;
        font-size: 24rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #C9CACA;
        margin-right: 10rpx;
        transition: border 0.3s;

        &.active {
			background-color :transparent;
          color: color-active;
          border-color: color-active;
        }
      }
    }
  }
}

.chart-tip {
  position: relative;
  display: flex;
  font-size: 24rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: color-white;
  line-height: 1;
  margin: 28rpx 0 12rpx;

  >.bd {
    flex: 1;
  }

  >.ft {
    position: relative;
    z-index: 3;
    display: flex;
    flex: 0 0 auto;

    .icon {
      display: block;
      width: 30rpx;
      height: 30rpx;
      margin-left: 10rpx;
      transition: all 0.3s;

      &.active {
        transform: rotate(180deg);
      }
    }

    >.text {
      display: flex;
      align-items: center;
    }

    .filter {
      position: absolute;
      z-index: 3;
      padding-top: 12rpx;
      top: 150%;
      right: 0;

      .options {
        position: relative;
        z-index: 3;
        border-radius: 10rpx;
        background: rgba(0, 0, 0, 0.7);
        padding: 16rpx;

        .option {
          height: 50rpx;
          line-height: 50rpx;
          text-align: center;
          color: #fff;
        }
      }

      .after {
        position: absolute;
        content: '';
        width: 0;
        height: 0;
        top: 0;
        right: 0;
        left: 0;
        margin: auto;
        border-left: 10rpx solid transparent;
        border-right: 10rpx solid transparent;
        border-bottom: 12rpx solid rgba(0, 0, 0, 0.7);
      }
    }
  }
}
</style>